package com.musemun.controller;

import com.google.zxing.WriterException;
import com.musemun.common.CommonResult;
import com.musemun.exception.MyDefineException;
import com.musemun.pojo.Crifo;
import com.musemun.pojo.ResultPhoto;
import com.musemun.service.CrifoService;
import com.musemun.service.CropifoService;
import com.musemun.util.TwoCodeUtil;
import com.musemun.util.UploadFileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

@RestController
@Api(tags = "二维码生成模块")
@RequestMapping("/two_dimensional_code")
public class TwoImageController {

    @Resource
    ExecutorService executorService;
    @Resource
    CrifoService crifoService;
    @Resource
    CropifoService cropifoService;
    @ApiOperation("这个暂时没用先的是本地地址，所有扫二维码会没用")
    @GetMapping("/by_image/{id}")
    public CommonResult<Crifo> queryCrifoByTwoDimensionalCode(@PathVariable long id){
        Crifo crifo=crifoService.getById(id);
        return new CommonResult<>(200,"查询成功",crifo);
    }
    /**
     *
     *  根据id返回文物的二维码
     * @param id  文物的id
     * @return void
     */
    @ApiOperation("通过id生成二维码")
    @GetMapping("/generator_image/{id}")
    public void getTwoImage(@PathVariable long id, HttpServletResponse response) throws IOException, WriterException {
        TwoCodeUtil.generateCodeBufferImage(id,response);
        response.flushBuffer();
    }

    /**
     *
     *
     * @param crifo  单张图片输入
     * @param file  输入的图片
     * @return com.musemun.common.CommonResult<com.musemun.pojo.ResultPhoto>
     */
    @ApiOperation("单张图片导入，图片不能为空")
    @PostMapping("/import_single_crifo")
    @ResponseBody
    public CommonResult<ResultPhoto> importSingleCrifo(Crifo crifo, @NotNull @RequestParam("file") MultipartFile file) throws IOException, WriterException {
        if(StringUtils.isEmpty(crifo.getCrName())){
            throw new MyDefineException(400,"请填写文物名称信息，至少需要填写文物名称");
        }
        String fileName= UUID.randomUUID().toString().replace("-", "")+".jpeg";
        executorService.execute(()->{
            try {
                UploadFileUtils.upload("/img/",file,fileName);

            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        crifo.setCrPic("/img/"+fileName);

        crifoService.save(crifo);
        cropifoService.insertCropifo(crifo,1);
        return new CommonResult<>(200,"插入条数据成功",new ResultPhoto(crifo));
    }
}
